package com.shijiu.component;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shijiu.dao.mapper.GoodsMapper;
import com.shijiu.dao.mapper.ShopOrderMapper;
import com.shijiu.pojo.Goods;
import com.shijiu.pojo.ShopOrder;
import com.shijiu.service.ShopOrderService;
import com.shijiu.service.impl.ShopOrderServiceImpl;
import io.swagger.annotations.ApiOperation;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author xlj
 * @Date Created in  2023/4/27 9:52
 * @DESCRIPTION:
 * @Version V1.0
 */

//@Component注解用于对那些比较中立的类进行注释；
//相对与在持久层、业务层和控制层分别采用 @Repository、@Service 和 @Controller 对分层中的类进行注释
@Component
// 1.开启定时任务
@EnableScheduling
/**
  2.开启多线程(定时任务检查删除订单)
 */
@EnableAsync
@SuppressWarnings("all")
public class MultithreadScheduleTask {
   @Resource
   private ShopOrderMapper shopOrderMapper;

   @Resource
   private GoodsMapper goodsMapper;

   @Resource
   private ShopOrderServiceImpl shopOrderServiceImpl;
   @Async
   @Scheduled(fixedDelay = 60000)
   @ApiOperation("/* 间隔1分钟定时检查数据库 */")
   public void first() throws InterruptedException {
      LambdaQueryWrapper<ShopOrder> wrapper = new LambdaQueryWrapper<>();
      wrapper.eq(ShopOrder::getStatus,"0").eq(ShopOrder::getIsDeleted,"0");
      //拿到所有的订单
      List<ShopOrder> shopOrderList = shopOrderMapper.selectList(wrapper);
      List<ShopOrder> filteredOrders = shopOrderList.stream()
              .filter(order -> Math.ceil(DateUtil.betweenMs(order.getCreateTime(), order.getOverTime())) / 60000.0  > 30) // 保留订单结束时间与创建时间间隔超过30分钟的订单
              .collect(Collectors.toList()); // 将满足条件的订单收集到一个新的集合中
      //double result = Math.ceil(DateUtil.betweenMs("2023-04-27 10:05:03", "2023-04-27 10:07:02") / 60000.0);
       // 对筛选出来的订单执行xxx操作
      System.out.println(filteredOrders);
      filteredOrders.forEach(order -> {
         // 对订单执行xxx操作，例如：
         String orderId = order.getId();
         //将原本的库存退回数据库
         Integer orderCount = order.getCount();
         //根据订单名称查询货物的编号
         String orderNames = order.getOrderName();
         LambdaQueryWrapper<Goods> queryWrapper = new LambdaQueryWrapper<>();
         queryWrapper.eq(Goods::getName,orderNames);
         Goods goods = goodsMapper.selectOne(queryWrapper);
         Goods goods1 = new Goods();
         goods1.setId(goods.getId());
         goods1.setStores(goods.getStores()+orderCount);
         shopOrderServiceImpl.deletedById(orderId);
      });
   }
}
